//
//  ScenicPlayCCell.m
//  ImGuider
//
//  Created by llt on 2017/4/19.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "ScenicPlayCCell.h"
#import "DownloadListDAO.h"
#import "RecordListDAO.h"
#import "CBAutoScrollLabel.h"
#import "IGAvPlayerManager.h"
@interface ScenicPlayCCell ()<IGAvPlayerManagerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *mainImageView;
//@property (weak, nonatomic) IBOutlet UILabel *describeLabel;
@property (weak, nonatomic) IBOutlet CBAutoScrollLabel *describeLabelView;
@property (weak, nonatomic) IBOutlet UILabel *describeLabel;

@property (weak, nonatomic) IBOutlet UIImageView *lockImageView;
@property (weak, nonatomic) IBOutlet UIView *maskView;

@property (weak, nonatomic) IBOutlet UILabel *downloadLabel;

@property (weak, nonatomic) IBOutlet UILabel *numLabel;

@property (nonatomic, strong) ScenicPoint *scenicPoint;

@property (nonatomic,strong)IGAvPlayerManager * manager;
@property (nonatomic,copy)NSString * playPath;
@end

@implementation ScenicPlayCCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.mainImageView.layer.borderColor = kThemeColor.CGColor;
    self.playBtn.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ScenicCellTryChangePlayStateWith:) name:kIGAvPlayerManagerState object:nil];
    self.maskView.alpha = 0.6;
   // self.maskView.backgroundColor = [UIColor blackColor];
    self.maskView.hidden = YES;
    self.numLabel.layer.cornerRadius = 10;
    self.numLabel.clipsToBounds = YES;
    self.numLabel.layer.borderColor = [UIColor whiteColor].CGColor;
    self.numLabel.layer.borderWidth = 1.f;
    self.numLabel.hidden = YES;
    self.downloadLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    
    self.describeLabelView.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.describeLabelView.textColor = kTitleColor;
    self.describeLabelView.font = Font(12);
    self.describeLabelView.textAlignment = NSTextAlignmentCenter;
    self.describeLabelView.pauseInterval = 0;
    self.describeLabelView.backgroundColor = [UIColor whiteColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setDownloadProgress) name:MCDownloadStartNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setDownloadProgress) name:MCDownloadStopNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setDownloadProgress) name:MCDownloadFinishNotification object:nil];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (IGAvPlayerManager *)manager {
    if (!_manager) {
        _manager = [IGAvPlayerManager shareManeger];
        _manager.delegate = self;
    }
    
    return _manager;
}
- (void)setSelect:(BOOL)select {
    _select = select;
    
    self.mainImageView.layer.borderWidth = _select ? 3:0;
    
    self.describeLabelView.hidden = !select;
    self.describeLabel.hidden = select;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.playBtn.selected = NO;
    if (_select ) {
        
        self.mainImageView.layer.borderWidth = _select ? 3:0;
    }
    if ([IGAvPlayerManager shareManeger].isPlay && [[IGAvPlayerManager shareManeger].currentURL isEqualToString:self.playPath]) {
        self.playBtn.selected = YES;
    }
}

- (void)updateProgressWith:(CGFloat)value {
    
    [self.playBtn setProgress:value];
}

- (IBAction)playMusice:(id)sender {
    
    if (self.playBtn.selected || !self.playPath) {
        [self.manager pause];
        return;
    }
    
    
    if (![AppManager sharedManager].allowWhenPlay && [AppManager sharedManager].networkState == AFNetworkReachabilityStatusReachableViaWWAN) {
        
        @weakify(self);
        [IGAlertView alertWithTitle:@"" message:MYLocalizedString(@"PUBLIC_NOWIFI_PLAY_ALERT_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_NOWIFI_PLAY_ALERT_COMMIT", nil) commit:^{
            @strongify(self);
            [AppManager sharedManager].allowWhenPlay = YES;
            if (![[IGAvPlayerManager shareManeger].currentURL isEqualToString:self.playPath]) {
                [self.manager playMusic:self.playPath withPlayType:PlayTry];
                
            }else{
                [self.manager play];
            }
        } cancel:nil];
        
        return;
    }
    
    if (![[IGAvPlayerManager shareManeger].currentURL isEqualToString:self.playPath]) {
        [self.manager playMusic:self.playPath withPlayType:PlayTry];
    }else{
        [self.manager play];
    }
}


- (void)ScenicCellTryChangePlayStateWith:(NSNotification *)notif
{
    NSInteger state = [notif.userInfo[kIGAvPlayerManagerState] integerValue];
    NSString  * url = notif.userInfo[kCurrentPlayURL];
    
    NSNumber * type = notif.userInfo[kPlayType];
    if (![url isEqualToString:self.playPath] || type.integerValue != PlayTry) {
        return;
    }
    switch (state) {
        case AVPlayerPlayStatePreparing:
        case AVPlayerPlayStateBeigin:
        case AVPlayerPlayStatePlaying:
        {
            self.playBtn.selected = YES;
        }
            break;
        case AVPlayerPlayStatePause:
        case AVPlayerPlayStateEnd:
        case AVPlayerPlayStateNotPlay:
            //case AVPlayerPlayStateNotKnow:
        {
            self.playBtn.selected = NO;
            [self.playBtn setProgress:0];
        }
            break;
        default:
        {
            //            self.playBtn.selected = NO;
            //            [self.playBtn setProgress:0];
        }
            break;
    }
}

- (void)configDataWith:(ScenicPoint *)scenicPoint {
    
    
    if ([scenicPoint.number isEqualToString:@"36"] ) {
        IGLog(@"---%@",scenicPoint);
    }
    self.scenicPoint = scenicPoint;
    
    if (!self.playBtn.hidden) {
        self.playBtn.hidden = YES;
    }
    
    self.playPath = scenicPoint.playpath;
    
    if (scenicPoint.number.length > 0 && scenicPoint.number.integerValue > 0) {
        self.numLabel.text =  scenicPoint.number;
        self.numLabel.hidden = NO;
    }else {
        self.numLabel.hidden = YES;
    }
    
    NSURL *url = [NSURL URLWithString:scenicPoint.pictureArray.firstObject];
    UIImage *placeHoder = [UIImage imageNamed:@"placeholder_squ"];
    
    [self.mainImageView setImageURL:url placeholderImage:placeHoder];
    self.describeLabel.text = scenicPoint.spotname;
    self.describeLabelView.text = scenicPoint.spotname;
    [self setDownloadProgress];
    
    if (scenicPoint.playpath.length > 0) {
        
        @weakify(self);
        [RecordListDAO QueryRecordPlayPath:scenicPoint.playpath Block:^(BOOL isContain) {
            @strongify(self);
            self.record = isContain;
        }];
    }
    
}

- (void)setRecord:(BOOL)record {
    _record = record;
    
    if (record) {
        self.maskView.hidden = NO;
    }else {
        self.maskView.hidden = YES;
    }
}

- (void)setDownloadProgress {
    
    if (!self.showProgress) {
        
        self.downloadLabel.hidden = YES;
        return;
    }
    
    self.downloadLabel.hidden = NO;
    
    MCDownloadReceipt *receipt = [[DownloadManager sharedManager] downloadReceiptForURLString:self.scenicPoint.playpath];
    
    if (receipt.state == MCDownloadStateDownloading) {
        
        self.downloadLabel.text = [NSString localizedStringWithFormat:MYLocalizedString(@"MYDOWNLOAD_STATE_DOWNLOADING", nil),receipt.progress.fractionCompleted * 100];
        
    } else if (receipt.state == MCDownloadStateCompleted) {
        
        self.downloadLabel.text = MYLocalizedString(@"MYDOWNLOAD_STATE_SUCCESS", nil);
        
    } else if (receipt.state == MCDownloadStateFailed) {
        
        self.downloadLabel.text = MYLocalizedString(@"MYDOWNLOAD_STATE_FAILED", nil);
        
    } else if (receipt.state == MCDownloadStateSuspened) {
        
        self.downloadLabel.text = MYLocalizedString(@"MYDOWNLOAD_STATE_SUSPEND", nil);
        
    } else {
        
        self.downloadLabel.text = MYLocalizedString(@"MYDOWNLOAD_STATE_WATINGDOWNLOAD", nil);
        
    }
    
    @weakify(self);
    receipt.downloaderProgressBlock = ^(NSInteger receivedSize, NSInteger expectedSize, NSInteger speed, NSURL * _Nullable targetURL) {
        @strongify(self);
        
        if (![targetURL.absoluteString isEqualToString:self.scenicPoint.playpath]) {
            
            return;
        }
        
        CGFloat progress = receivedSize * 1.0f / expectedSize;
        
        if (progress == 1) {
            self.downloadLabel.text = MYLocalizedString(@"MYDOWNLOAD_STATE_SUCCESS", nil);
            return;
        }
        
        if (progress >= 1) {
            progress = 1;
        } else if (progress < 0) {
            progress = 0;
        }
        
        self.downloadLabel.text = [NSString localizedStringWithFormat:MYLocalizedString(@"MYDOWNLOAD_STATE_DOWNLOADING", nil),progress * 100];
    };
    
    receipt.downloaderCompletedBlock = ^(MCDownloadReceipt *receipt, NSError * _Nullable error, BOOL finished) {
        @strongify(self);
        if (![receipt.url isEqualToString:self.scenicPoint.playpath]) {
            
            return;
        }
        
        if (error) {
            self.downloadLabel.text = MYLocalizedString(@"MYDOWNLOAD_STATE_FAILED", nil);
            IGLog(@"总进度------ cell 下载失败 %@",self.scenicPoint.spotname);
            
        } else {
            
            self.downloadLabel.text = MYLocalizedString(@"MYDOWNLOAD_STATE_SUCCESS", nil);
            IGLog(@"总进度------ cell 已下载 %@",self.scenicPoint.spotname);
        }
    };
    
}

@end
